package vh.sphynx.scoping;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.xtext.scoping.impl.ImportUriResolver;

import vh.sphynx.sphynx.IncludeStatement;

public class SphynxImportUriResolver extends ImportUriResolver {
	
	public static List<String> searchPath = new ArrayList<String>();
	public static Map<EObject, String> resolved = new HashMap<EObject, String>();
	
	@Override
	public String apply(EObject from) {
		String s = resolved.get(from);
		if (s == null && from instanceof IncludeStatement)
			resolved.put(from, s = resolve((IncludeStatement)from));
		return s;
	}
	
	public static void addPaths(String paths) {
		if (paths != null)
			for(String path: paths.split(";")) {
				String p = path.trim();
				if (p.length() > 0) {
					if (!p.endsWith("/")) p += "/";
					SphynxImportUriResolver.searchPath.add(p);
				}
			}
	}

	private String resolve(IncludeStatement from) {
		if (from.isSearchPathUsed()) {
			String file = from.getImportURI();
			for (String path: searchPath)
				if (new File(path + file).exists())
					return URI.createFileURI(new File(path + file).getAbsolutePath()).toString();
		}
		
		URI resuri = from.eResource().getURI();
		
		String path = resuri.isFile() ? "file:/" + new File(resuri.toFileString()).getParent() : "";
		if (resuri.isPlatformResource()) {
			path = resuri.toString();
			int idx = path.lastIndexOf("/");
			path = path.substring(0, idx);
		}
		String uri = from.getImportURI();
		if (!uri.startsWith("platform:/"))
			uri = URI.createURI(path + "/" + uri).toString();
		return uri;
	}

}
